package com.haotunet.app.goldtreasure.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.haotunet.app.goldtreasure.R;
import com.haotunet.app.goldtreasure.model.BaseModel;
import com.haotunet.app.goldtreasure.model.OrderInfo;
import com.haotunet.app.goldtreasure.model.SellPageInfo;
import com.haotunet.app.goldtreasure.net.ActionUtil;
import com.haotunet.app.goldtreasure.other.Interface.OnPassBackListener;
import com.haotunet.app.goldtreasure.other.Interface.OnValueSetClickListener;
import com.haotunet.app.goldtreasure.utils.ActivityUtils;
import com.haotunet.app.goldtreasure.utils.ShareStore;
import com.haotunet.app.goldtreasure.utils.StringConvertNumber;
import com.haotunet.app.goldtreasure.utils.Strs;
import com.haotunet.app.goldtreasure.utils.UIHelper;
import com.haotunet.app.goldtreasure.utils.Utils;
import com.haotunet.app.goldtreasure.views.DialogWidget;
import com.haotunet.app.goldtreasure.views.PayPasswordView;
import com.haotunet.app.goldtreasure.views.PayPasswordView.OnPayListener;
import com.haotunet.app.goldtreasure.views.ReBuyRemindPopupView;
import com.haotunet.app.goldtreasure.views.TipPopupView;
import com.haotunet.app.goldtreasure.views.TitleView;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.tongdun.android.shell.FMAgent;

public class SellGoldActivity extends BaseActivity {
    private final int GET_SELLPAGE_INFO_SUCCESS = 1;
    private final int SELL_GOLD_OPERATIN_SUCCESS = 2;
    @InjectView(R.id.title_view_sell)
    TitleView titleViewSell;
    @InjectView(R.id.txt_current_gold_price)
    TextView txtCurrentGoldPrice;
    @InjectView(R.id.txt_account_gold_gram)
    TextView txtAccountGoldGram;
    @InjectView(R.id.txt_sell_grams)
    TextView txtSellGrams;
    @InjectView(R.id.et_sell_grams)
    EditText etSellGrams;
    @InjectView(R.id.txt_gram)
    TextView txtGram;
    @InjectView(R.id.tv_estimated_amount)
    TextView tvEstimatedAmount;
    @InjectView(R.id.fees_tip)
    TextView feesTip;
    @InjectView(R.id.tip_layout)
    LinearLayout tipLayout;
    @InjectView(R.id.btn_sell)
    Button btnSell;
    @InjectView(R.id.root)
    LinearLayout root;
    private String gold_price;
    private String gold_gram;
    private String inputGrams;
    private String counter_fee;
    private OrderInfo orderInfo;
    private DialogWidget mDialogWidget;
    private SellPageInfo spInfo;
    private Handler handle = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GET_SELLPAGE_INFO_SUCCESS:
                    spInfo = (SellPageInfo) msg.obj;
                    counter_fee = spInfo.getFee();
                    gold_gram = spInfo.getAvailableGold();
                    gold_price = spInfo.getCurrentGoldPrice();
                    txtAccountGoldGram.setText(gold_gram);
                    txtCurrentGoldPrice.setText(gold_price);
                    break;
                case SELL_GOLD_OPERATIN_SUCCESS:
                    orderInfo = (OrderInfo) msg.obj;
                    if (orderInfo.getStatus().equals("0")) {
                        showSellDialog();
                    } else {
                        gold_price = orderInfo.getCurrentGoldPrice();
                        String message = orderInfo.getMsg();
                        showGoldPriceChangeView(message, gold_price);
                    }
                    break;
                default:
                    break;
            }
        }

    };
    private PayPasswordView passwordView;
    private ShareStore shareStore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sell_gold);
        ButterKnife.inject(this);
        shareStore = new ShareStore(SellGoldActivity.this);
        initView();
        getSellPageInfo();
    }

    private void getSellPageInfo() {
        ActionUtil actionUtil = new ActionUtil(SellGoldActivity.this);
        actionUtil.getSellGoldPageInfo();
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()) {
                    return;
                }
                SellPageInfo spInfo = (SellPageInfo) model;
                if (spInfo == null) {
                    UIHelper.showToast(SellGoldActivity.this, getString(R.string.rank_fail));
                    return;
                }
                if (spInfo.getErrorMsg() != null) {
                    if (spInfo.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(SellGoldActivity.this, getString(R.string.crowding_in_tips_txt));
                    } else {
                        UIHelper.showToast(SellGoldActivity.this, spInfo.getErrorMsg());
                    }
                } else {
                    Message msg = new Message();
                    msg.what = GET_SELLPAGE_INFO_SUCCESS;
                    msg.obj = spInfo;
                    handle.sendMessage(msg);
                }
            }
        });
    }

    private void initView() {
        titleViewSell.getTitletextView().setVisibility(View.VISIBLE);
        titleViewSell.getTitletextView().setText(getString(R.string.sell_gold));
        titleViewSell.getBackView().setVisibility(View.VISIBLE);
        initEditextListener();
        setBtnInvalid();
    }

    private void initEditextListener() {
        etSellGrams.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String inputString = s.toString();
                if (inputString.contains(".")) {
                    if (inputString.length() - 1 - inputString.toString().indexOf(".") > 3) {
                        inputString = (String) inputString.subSequence(0, inputString.indexOf(".") + 4);
                        etSellGrams.setText(inputString);
                        etSellGrams.setSelection(inputString.length());
                    }
                }
                if (inputString.trim().substring(0).equals(".")) {
                    inputString = "";
                    etSellGrams.setText(inputString);
                }
                if (inputString.startsWith("0") && inputString.trim().length() > 1) {
                    if (!inputString.substring(1, 2).equals(".")) {
                        etSellGrams.setText(inputString.subSequence(1, 2));
                        etSellGrams.setSelection(1);
                        return;
                    }
                }
                if (inputString.length() == 0) {
                    tvEstimatedAmount.setText("0.00");
                    feesTip.setVisibility(View.GONE);
                    setBtnInvalid();
                } else {
                    if (!TextUtils.isEmpty(gold_price)) {
                        double inputGram = StringConvertNumber.parseDouble(inputString.toString());
                        double accountGold = StringConvertNumber.parseDouble(gold_gram);
                        double goldPrice = Double.parseDouble(gold_price.toString());
                        double counterFee = Double.parseDouble(counter_fee);
                        String fees = Utils.decimalMultiplyKeepTwoPlaces(inputGram, counterFee);
                        if (inputGram == 0) {
                            setBtnInvalid();
                            tvEstimatedAmount.setText("0.00");
                            feesTip.setVisibility(View.GONE);
                        } else if (0 < inputGram && inputGram <= accountGold) {
                            setBtnValid();
                            tvEstimatedAmount.setText(Utils.decimalMultiplyKeepTwoPlaces(inputGram,
                                    Utils.decimalReduceKeepTwoPlaces(goldPrice, counterFee)));
                            feesTip.setVisibility(View.VISIBLE);
                            feesTip.setTextColor(getResources().getColor(R.color.color_585858));
                            feesTip.setText("已扣除手续费" + fees + "元");
                        } else {
                            setBtnInvalid();
                            feesTip.setText("超出账户黄金克数");
                            feesTip.setVisibility(View.VISIBLE);
                            tvEstimatedAmount.setText(Utils.decimalMultiplyKeepTwoPlaces(inputGram,
                                    Utils.decimalReduceKeepTwoPlaces(goldPrice, counterFee)));
                            feesTip.setTextColor(getResources().getColor(R.color.color_red));
                        }
                    }
                }
            }
        });
    }

    private void sellGoldOperation() {
        ActionUtil actionUtil = new ActionUtil(SellGoldActivity.this);
        actionUtil.sellGoldOperation(gold_price, inputGrams);
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()) {
                    return;
                }
                OrderInfo orderModel = (OrderInfo) model;
                if (orderModel == null) {
                    UIHelper.showToast(SellGoldActivity.this, getString(R.string.rank_fail));
                    return;
                }
                if (orderModel.getErrorMsg() != null) {
                    if (orderModel.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(SellGoldActivity.this, getString(R.string.crowding_in_tips_txt));
                    } else {
                        UIHelper.showToast(SellGoldActivity.this, orderModel.getErrorMsg());
                    }
                } else {
                    Message msg = new Message();
                    msg.what = SELL_GOLD_OPERATIN_SUCCESS;
                    msg.obj = orderModel;
                    handle.sendMessage(msg);
                }
            }
        });

    }

    protected void showSellDialog() {
        mDialogWidget = new DialogWidget(SellGoldActivity.this, getDecorViewDialog());
        mDialogWidget.show();
    }

    protected void submitSelldata(String blackBox, String orderNo, final String payPassword) {
        ActionUtil actionUtil = new ActionUtil(SellGoldActivity.this);
        actionUtil.submitSellGoldData(blackBox, orderNo, payPassword);
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()) {
                    return;
                }
                if (model == null) {
                    UIHelper.showToast(SellGoldActivity.this, getString(R.string.rank_fail));
                    return;
                }
                if (model.getErrorMsg() != null) {
                    if (model.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(SellGoldActivity.this, getString(R.string.crowding_in_tips_txt));
                    } else {
                        UIHelper.showToast(SellGoldActivity.this, model.getErrorMsg());
                        passwordView.clearUi();
                    }
                } else {
                    if ("true".equals(model.getStatus())) {
                        passwordView.showSuccessUi();
                        new Thread(new Runnable() {
                            public void run() {
                                try {
                                    Thread.sleep(1000);
                                    ActivityUtils.gotoMyWallet(SellGoldActivity.this);
                                    if (mDialogWidget != null) {
                                        mDialogWidget.dismiss();
                                    }
                                    mDialogWidget = null;
                                    SellGoldActivity.this.finish();
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    } else {
                        passwordView.clearUi();
                        passwordView.setErrorTip(model.getInfo());
                    }
                }
            }
        });
    }

    protected View getDecorViewDialog() {
        if (shareStore.getInt(Strs.IS_HAD_TRADING_PWD, 0) == 1) {
            passwordView = new PayPasswordView(2, 2, SellGoldActivity.this, null, "", null);
        } else {
            passwordView = new PayPasswordView(1, 2, SellGoldActivity.this, null, "", null);
        }
        passwordView.setOnPayListener(new OnPayListener() {

            @Override
            public void onSurePay(String password) {
                String blackBox = FMAgent.onEvent(SellGoldActivity.this);
                submitSelldata(blackBox, orderInfo.getOrderNo(), password);
            }

            @Override
            public void onCancelPay() {
                mDialogWidget.dismiss();
                mDialogWidget = null;
            }
        });
        return passwordView.getView();
    }

    protected void showGoldPriceChangeView(final String message, final String goldPrice) {
        ReBuyRemindPopupView reBuyPopup = new ReBuyRemindPopupView(SellGoldActivity.this, message, goldPrice, 1);
        reBuyPopup.showAtLocation(root, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
        reBuyPopup.setValueSetClickListener(new OnValueSetClickListener() {

            @Override
            public void onValueSet(String value) {
                if (value.equals("ok")) {
                    sellGoldOperation();
                } else if (value.equals("cancle")) {
                    txtCurrentGoldPrice.setText(goldPrice);
                }
            }
        });
    }

    private void setBtnValid() {
        btnSell.setBackgroundResource(R.drawable.login_btn_bg_formal);
        btnSell.setEnabled(true);
    }

    private void setBtnInvalid() {
        btnSell.setBackgroundResource(R.drawable.login_btn_bg_unclick);
        btnSell.setEnabled(false);
    }

    @OnClick({R.id.iv_back, R.id.tip_layout, R.id.btn_sell})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tip_layout:
                if (spInfo != null) {
                    new TipPopupView(SellGoldActivity.this, null, spInfo.getTips(), R.style.MyDialog).show();
                }
                break;
            case R.id.btn_sell:
                inputGrams = etSellGrams.getText().toString();
                sellGoldOperation();
                break;
        }
    }
}
